import settings from "../utils/settings";
import { location } from "../utils/getLocation";
import { guiMover } from "../utils/gui";
import { getPlayerPos, DrawString, drawBoxAtPos, insertStr, timedisplay, waypoints, MessageID, getItemSBID, isModLoaded, stripRank, partylist, newItemStackFrom, rayTrace, drawQuadsAtPos, ServerTick } from "../utils/utils";
import { Vec3 } from "../utils/vec3";
import BeaconBeam from "../../BeaconBeam";
import petmanager from "../utils/petmanager";

export function mining() {

//CH /warp nucleus
let warpready = null;
register("chat", () => {
	if(!settings.nucleus){return};
    if(warpready == null || Date.now() - warpready > 10000){
        ChatLib.chat("§6§l[BZA] §b准备/warp nucleus,再点一下水晶进行传送")
        warpready = Date.now();
    }else if(Date.now() - warpready > 500){
        ChatLib.command(`warp nucleus`)
        warpready = Date.now() + 10000;
    }
}).setChatCriteria("You have already obtained this Crystal!");

//Mining Abilit is now available!
function isPickaxe(item) {
    if(typeof(item) != "Item") return false;
    return ([270,274,257,285,278].indexOf(item.getID()) != -1);
}
function isHoldingDrill() {
    let holdingItem = Player.getHeldItem();
    if(!holdingItem) return false;
    let id = holdingItem.getNBT().getCompoundTag("tag").getCompoundTag("ExtraAttributes").getString("id");
    return (isPickaxe(holdingItem) || id.includes("DRILL") || id.includes("PICKAXE") || id.includes("GAUNTLET"));
}
register("chat", (ability) => {
    if(!settings.MiningAbilit || !location.inSkyblock || location.inDungeon) return;
    if(isHoldingDrill() || location.island == "Dwarven Mines" || location.island == "Crystal Hollows"){
        World.playSound("note.pling", 1, 1.5);
        Client.showTitle("" , "§6" + ability + " §ais now available!" , 0 , 30 , 5);
    }
}).setCriteria("${ability} is now available!")
register("chat", (ability) => {
    if(!settings.MiningAbilit || !location.inSkyblock || location.inDungeon) return;
    if(isHoldingDrill() || location.island == "Dwarven Mines" || location.island == "Crystal Hollows"){
        Client.showTitle("" , "§aYou used your §6" + ability + " §aPickaxe Ability!" , 0 , 20 , 10);
    }
}).setCriteria("You used your ${ability} Pickaxe Ability!")
register("chat", (ability) => {
    if(!settings.MiningAbilit || !location.inSkyblock || location.inDungeon) return;
    if(isHoldingDrill() || location.island == "Dwarven Mines" || location.island == "Crystal Hollows"){
        World.playSound("note.pling", 1, 0.5);
        Client.showTitle("" , "§cYour " + ability + " has expired!" , 0 , 20 , 10);
    }
}).setCriteria("Your ${ability} has expired!")

//水晶矿洞通行证自动续费
register("chat",() => {
    ChatLib.command("purchasecrystallhollowspass");
}).setChatCriteria("Click here to purchase a new 6 hour pass for 10,000 Coins")
    
//Crystal Hollows Chest
let chests = [];
register("worldLoad",() => { chests = [] })
register("step",() => {
    if(!settings.BoxCHChest || !location.inSkyblock || location.island != "Crystal Hollows") return;
    chests = World.getAllTileEntities().filter(e => e.getBlockPos().distance(new BlockPos(Player.getX(),Player.getY(),Player.getZ())) < 16 && e.getBlockType().getRegistryName() === "minecraft:chest");
}).setDelay(1)

register("renderWorld" , (ticks) => {
    if(chests.length != 0) chests.forEach(e => {drawBoxAtPos(e.getX(),e.getY(),e.getZ(),1,0,0,1,1,1,1,4,(settings.BoxCHChest == 2.0 ? true : false))})
})

//crystal hollows getfromsacks
let CHGetFromSacksCoolDown = 0;
let gettingApparatus = false;
register("chat", (event) => {
    if(CHGetFromSacksCoolDown > ServerTick.getTime()) return;
    if(!settings.CHgetfromsacks || !location.inSkyblock || location.island != "Crystal Hollows") return;
    let message = ChatLib.getChatMessage(event,false).removeFormatting();
    switch (message) {
        case "[NPC] Kalhuiki Door Guardian: This temple is locked, you will need to bring me a key to open the door!":
            if(Player.getInventory().getItems().filter(e => e && getItemSBID(e) === "JUNGLE_KEY").length != 0) return;
            ChatLib.command("getfromsacks jungle key 1");
            CHGetFromSacksCoolDown = ServerTick.getTime() + 1600;
            break;
        case "[NPC] King Yolkar: Bring me any type of Goblin Egg and we can show the Goblin Queen what it's like to lose something she loves!":
        case "[NPC] King Yolkar: Where is my Goblin Egg? My Chef is waiting!":
        case "[NPC] King Yolkar: That is certainly not the meal I am looking for! Bring me back some Goblin Egg and you will satiate my hunger.":
            if(Player.getInventory().getItems().filter(e => e && getItemSBID(e) === "GOBLIN_EGG").length != 0) return;
            ChatLib.command("getfromsacks goblin egg 1");
            CHGetFromSacksCoolDown = ServerTick.getTime() + 1600;
            break;
        case "[NPC] Professor Robot: Bring me all 6 key components to the giant so that I can repair it!":
        case "[NPC] Professor Robot: That's not one of the components I need! Bring me one of the missing components:":
            if(Player.getInventory().getItems().filter(e => e && getItemSBID(e) === "PRECURSOR_APPARATUS").length != 0) return;
            ChatLib.command("viewrecipe PRECURSOR_APPARATUS");
            gettingApparatus = true;
            break;
    }
})

register("chat", () => {
    if(!settings.CHgetfromsacks || !location.inSkyblock || location.island != "Crystal Hollows") return;
    if(!gettingApparatus) return;
    Client.currentGui.close();
    gettingApparatus = false;
}).setCriteria("You Supercrafted Precursor Apparatus!")

//worm && scatha   (TryToFeel)
let scatha = 0;
register("chat", () => {
    if(settings.Scatha && location.inSkyblock && location.island == "Crystal Hollows") scatha = ServerTick.getTime();
}).setCriteria("You hear the sound of something approaching...")

register("renderOverlay",() => {
    if(!settings.Scatha) return;
    if(guiMover.gui.isOpen()) {
        DrawString("§5§lScatha: §a§l30.000s", guiMover.settings.Scatha.x , guiMover.settings.Scatha.y , guiMover.settings.Scatha.s , true);
        return;
    }
    if(location.island != "Crystal Hollows" || (settings.Scatha == 1.0 && ServerTick.getTime() - scatha > 30000)) return;
    DrawString("§5§lScatha: §8§l" + (ServerTick.getTime() - scatha > 30000 ? "§a§lReady" : (timedisplay(30000 - (ServerTick.getTime() - scatha))) ), guiMover.settings.Scatha.x , guiMover.settings.Scatha.y , guiMover.settings.Scatha.s , true);
})

//Armadillo Energy
let energy = { dillo : false , now : 0 , max : 0 }
register("worldLoad" , () => { energy.dillo = false; energy.now = 0; energy.max = 0; })
function ColorArmadilloString(str) {
    return "§e" + insertStr(str,parseInt(str.length * energy.now / energy.max),"§f");
}

register("step" , () => {
    if(!location.inSkyblock || location.island != "Crystal Hollows") return;
    if((petmanager.getPet() && petmanager.getPet().getName() == "ARMADILLO") || Player.getPlayer().field_70154_o) energy.dillo = true; else energy.dillo = false;
    if(!energy.max || energy.dillo == false || Player.getPlayer().field_70154_o) return;  //ridingEntity
    if(energy.now + energy.max / 300 < energy.max) energy.now = Math.floor((energy.now + energy.max / 300) * 10) / 10; else energy.now = energy.max;
}).setDelay(1)

register("actionBar" , (now,max) => {
    if(!location.inSkyblock || location.island != "Crystal Hollows") return;
    energy.now = now * 1.0; energy.max = max * 1.0;
}).setCriteria(/Armadillo Energy:[ ]+([0-9]{1,3}[.]?[0-9]?)\/([0-9]{1,3}[.]?[0-9]?)/)

register("renderOverlay" , () => {
    if(!settings.ArmadilloEnergy) return;
    if(guiMover.gui.isOpen()) {DrawString("§eArmad§fillo 114/300" , guiMover.settings.Dillo.x , guiMover.settings.Dillo.y , guiMover.settings.Dillo.s , true); return;}
    if((settings.ArmadilloEnergy == 2.0 || energy.now < energy.max ) && energy.dillo && energy.max) DrawString(ColorArmadilloString("Armadillo " + energy.now + "/" + energy.max) , guiMover.settings.Dillo.x , guiMover.settings.Dillo.y , guiMover.settings.Dillo.s , true);
})

register("chat" , () => {
    if(!location.inSkyblock || location.island != "Crystal Hollows") return;
    energy.now = energy.max;
    if(settings.ArmadilloFullEnergy && settings.ArmadilloFullEnergy != 2.0) Client.showTitle("",settings.ArmadilloFullEnergyTitle,0,40,10);
    if(settings.ArmadilloFullEnergy && settings.ArmadilloFullEnergy != 1.0) World.playSound("random.burp",1,1);
}).setCriteria("Your armadillo is full of energy!")


//CrystalWishingCompassSolver
const DOUBLE_EPSILON = 4.94065645841247E-324;

/**
 * 交点计算方法来自NEU并略改 https://github.com/NotEnoughUpdates/NotEnoughUpdates     
 * NEU里说: Based on http://paulbourke.net/geometry/pointlineplane/calclineline.cs
 * @param {Vec3} p1 第一条线的起点的 x y z 坐标
 * @param {Vec3} p2 第一条线的终点的 x y z 坐标
 * @param {Vec3} p3 第二条线的起点的 x y z 坐标
 * @param {Vec3} p4 第二条线的终点的 x y z 坐标
 * @returns {Vec3i | null} 交叉点的 x y z 坐标,如果没有则返回 null
 */
function getIntersectionPoint(p1,p2,p3,p4) {
    const p13 = p1.subtract(p3);
    const p43 = p4.subtract(p3);

    if (p43.lengthSquared() < DOUBLE_EPSILON) {
        return null;
    }

    const p21 = p2.subtract(p1);
    if (p21.lengthSquared() < DOUBLE_EPSILON) {
        return null;
    }

    const d1343 = p13.x * p43.x + p13.y * p43.y + p13.z * p43.z;
    const d4321 = p43.x * p21.x + p43.y * p21.y + p43.z * p21.z;
    const d1321 = p13.x * p21.x + p13.y * p21.y + p13.z * p21.z;
    const d4343 = p43.x * p43.x + p43.y * p43.y + p43.z * p43.z;
    const d2121 = p21.x * p21.x + p21.y * p21.y + p21.z * p21.z;

    const denom = d2121 * d4343 - d4321 * d4321;
    if (Math.abs(denom) < DOUBLE_EPSILON) {
        return null;
    }
    const numer = d1343 * d4321 - d1321 * d4343;

    const mua = numer / denom;
    const mub = (d1343 + d4321 * (mua)) / d4343;

    return new Vec3i(
        ((p1.x + mua * p21.x) + (p3.x + mub * p43.x)) / 2,
        ((p1.y + mua * p21.y) + (p3.y + mub * p43.y)) /2,
        ((p1.z + mua * p21.z) + (p3.z + mub * p43.z)) /2
    );
}


let KingsFoul = 0;
register("chat", () => {
    if(location.inSkyblock && location.island == "Crystal Hollows") KingsFoul = 0;
}).setCriteria("The Goblin King's foul stench has dissipated!")
register("worldLoad", () => { KingsFoul = 0; })

register("playerInteract", (action,pos,event) => {
    if(!location.inSkyblock || location.island != "Crystal Hollows" || location.location != "Goblin Holdout") return;
    if(KingsFoul != 0) return;
    if(action.toString() != "RIGHT_CLICK_EMPTY") return;
    let entity = Player.lookingAt();
    if(!entity || entity instanceof Entity == false) return;
    if(entity.getClassName() != "EntityOtherPlayerMP" || entity.getYaw() != 0 || entity.getPitch() != 90) return;
    let item = Player.getHeldItem();
    if(!item || !getItemSBID(item).startsWith("GOBLIN_EGG")) return;
    KingsFoul = Date.now() + 20 * 60 * 1000;
})
register("attackEntity", (entity,event) => {
    if(!location.inSkyblock || location.island != "Crystal Hollows" || location.location != "Goblin Holdout") return;
    if(KingsFoul != 0) return;
    if(entity.getClassName() != "EntityOtherPlayerMP" || entity.getYaw() != 0 || entity.getPitch() != 90) return;
    let item = Player.getHeldItem();
    if(!item || !getItemSBID(item).startsWith("GOBLIN_EGG")) return;
    KingsFoul = Date.now() + 20 * 60 * 1000;
})

/**
 * 看看指南针指到哪里
 * @param {Vec3i} pos 指南针指向的目的地
 * @returns {string | null} 目的地的名字
 */
function getCompassTarget(pos) {
    if(462 < pos.x && pos.x < 564 && 462 < pos.z && pos.z < 564) return "Crystal Nucleus";
    if(pos.y <= 63) return "§cBal";
    if(pos.x < 513 && pos.z < 513) {
        if(Player.getInventory().getItems().filter(e => e && e.getName().removeFormatting() == "Jungle Key").length) return "§aJungle Temple";
        return "§aOdawa";
    } else if(pos.x < 513 && pos.z > 512) {
        if(KingsFoul > Date.now()) return "§eGoblin Queen's Den";
        return "§6King Yolkar";
    } else if(pos.x > 512 && pos.z < 513) {
        return "§aMines of Divan";
    } else if(pos.x > 512 && pos.z > 512) {
        if((location.location == "Goblin Holdout" || location.location == "Goblin Queen's Den") && pos.x < 560) {
            if(KingsFoul > Date.now()) return "§eGoblin Queen's Den";
            return "§6King Yolkar";
        }
        return "§bLost Precursor City";
    }
    return "Unknow";
}

//Wishing Compass Solver
let currentCompass = []; let previousCompass = []; let solverStatus = "";
register("worldLoad", () => {
    solverStatus = "";
    CheckParticle.unregister();
    currentCompass = [];
    previousCompass = [];
})

register("playerInteract", (action,position,event) => {
    if(!settings.WishingCompassSolver || !location.inSkyblock || location.island != "Crystal Hollows") return;
    if(!action.toString().includes("RIGHT_CLICK") || Player.getHeldItem()?.getName()?.removeFormatting() != "Wishing Compass") return;
    if(location.location == "Crystal Nucleus") {ChatLib.simulateChat("§6[BZA] §e不推荐在晶核用,先出晶核吧");cancel(event);return;}
    if(solverStatus == "CheckParticle") {ChatLib.simulateChat("§6[BZA] §e需要先等待上一个指南针结束后再使用下一个");cancel(event);return;}
    if(currentCompass[0] && getPlayerPos().distance(currentCompass[0]) < 10) {ChatLib.simulateChat("§6[BZA] §e当前距离上一次使用指南针的地方太近了,需要走开一点再使用");cancel(event);return;}
    CheckParticle.register(); solverStatus = "CheckParticle";
    setTimeout(() => { CheckParticle.unregister();solverStatus = "Waiting"; }, 3500);
    if(currentCompass[1] && !previousCompass[1]) {
        previousCompass = currentCompass;
        currentCompass = [];
    }
})

const CheckParticle = register("spawnParticle", (particle,type,event) => {
    if(!location.inSkyblock || location.island != "Crystal Hollows") return;
    if(type.toString() != "VILLAGER_HAPPY") return;
    try {
        let pos = new Vec3(particle.getX(), particle.getY(), particle.getZ());
        if(currentCompass.length == 0) {
            if(pos.distance(getPlayerPos()) < 10) currentCompass[0] = pos;
            return;
        };
        if(pos.distance(currentCompass[0]) > 16) return;
        if(currentCompass.length < 2 || pos.distance(currentCompass[0]) > currentCompass[1].distance(currentCompass[0])) {
            currentCompass[1] = pos;
        } else {
            CheckParticle.unregister();
            if(currentCompass.length == 2 && previousCompass.length == 2) {
                ChatLib.deleteChat(MessageID.WishingCompass);
                let pos = getIntersectionPoint(currentCompass[0],currentCompass[1],previousCompass[0],previousCompass[1]);
                if(pos) {
                    let name = getCompassTarget(pos).replaceFormatting();
                    let cmd = settings.WishingCompassCMD.replace("%name%",name).replace("%x%",pos.x).replace("%y%",pos.y).replace("%z%",pos.z);
                    if(cmd.startsWith("//")) cmd = cmd.replace("//","/");
                    if(settings.WishingCompassText) new Message(
                        new TextComponent(
                            settings.WishingCompassText.replace("%name%",name).replace("%x%",pos.x).replace("%y%",pos.y).replace("%z%",pos.z))
                        .setClick("run_command",cmd)
                    ).setRecursive(true).chat();
                    if(settings.WishingCompassCMD.startsWith("//")) ChatLib.command(cmd.replace("/",""),true);
                }
                currentCompass = []; previousCompass = [];
            } else {
                ChatLib.simulateChat(new Message("§6[BZA] §e还需要再次使用指南针来定位目标").setChatLineId(MessageID.WishingCompass));
            }
        }
    } catch (error) { }
}).unregister();

//左键锁定
const AttackKeyBind = new KeyBind(Client.getMinecraft().field_71474_y.field_74312_F);
const MiningIsland = ["Gold Mine","Deep Caverns","Dwarven Mines","Mineshaft","Crystal Hollows"]
let KeyLocked = false;
let PressedTime = 0;
AttackKeyBind.registerKeyDown(() => { PressedTime++ })
AttackKeyBind.registerKeyRelease(() => {
    if(settings.MinesLeftLock == 0 || !location.inSkyblock) return;
    if(MiningIsland.indexOf(location.island) === -1) return;
    if(KeyLocked) KeyLocked = false;
    else if(PressedTime >= settings.MinesLeftLock * 20) {
        AttackKeyBind.setState(true);
        KeyLocked = true;
        Client.showTitle("","§a左键锁定 已激活",0,30,10);
        World.playSound("random.orb",1,1);
    }
    PressedTime = 0;
})

//更改挖粉音效
const Vault_open_shutter = {source:"Vault_open_shutter.ogg",category:"block",volume:1,attenuation:2};
const Vault_activate = {source:"Vault_activate.ogg",category:"block",volume:1,attenuation:2};
let BlockBreakTimer = 0;
register("soundPlay", (pos,name,vol,pit,cate,event) => {
    if(!location.inSkyblock || location.island != "Crystal Hollows") return;
    if(!settings.PowderMinerSoundChange) return;
    if(BlockBreakTimer < Date.now()) return;
    if(name == "random.orb") cancel(event);
    if(settings.PowderMinerSoundChange != 2) return;
    if(name == "random.chestopen") {
        cancel(event);
        new Sound(Vault_open_shutter).setPosition(pos.getX(),pos.getY(),pos.getZ()).play();
    }
    if(name == "random.levelup") {
        cancel(event);
        new Sound(Vault_activate).setPosition(pos.getX(),pos.getY(),pos.getZ()).play();
    }
})
register("hitBlock", () => {
    if(settings.PowderMinerSoundChange) BlockBreakTimer = Date.now() + 5000;
})

//Dark Monolith
const DarkMonolithLocation = [
    new BlockPos(-94,201,-30),
    new BlockPos(-91,221,-53),
    new BlockPos(-64,206,-63),
    new BlockPos(-15,236,-92),
    new BlockPos(-10,162,109),
    new BlockPos(1,170,0),
    new BlockPos(1,183,25),
    new BlockPos(49,202,-162),
    new BlockPos(56,214,-25),
    new BlockPos(61,204,181),
    new BlockPos(77,160,162),
    new BlockPos(91,187,131),
    new BlockPos(128,187,58),
    new BlockPos(150,196,190)
]
let ShowDarkMonolithLocation = DarkMonolithLocation;
let ResetingDarkMonolithLocation = 0;

register("renderWorld", () => {
    if(!location.inSkyblock) return;
    if(settings.DarkMonolithFinder == 0) return;
    if(location.island != "Dwarven Mines") return;
    if(ShowDarkMonolithLocation.length == 0) return;
    let playerPos = getPlayerPos();
    ShowDarkMonolithLocation.forEach(pos => {
        BeaconBeam(pos.x,pos.y,pos.z,102/255,0,204/255,0.5,true);
        Tessellator.drawString((ShowDarkMonolithLocation.length <= 1 ? "§5§l❀ " : "§5") + "Dark Monolith §6(" + parseInt(playerPos.distance(pos)) + "m)",pos.x+0.5,pos.y+0.5,pos.z+0.5,0,true,0.8,true);
    })
})

register("step", () => {
    if(!location.inSkyblock) return;
    if(settings.DarkMonolithFinder == 0) return;
    if(location.island != "Dwarven Mines") return;
    if(ShowDarkMonolithLocation.length == 0) {
        if(ResetingDarkMonolithLocation > 0) {
            if(ResetingDarkMonolithLocation < Date.now()) {
                ShowDarkMonolithLocation = DarkMonolithLocation;
                ResetingDarkMonolithLocation = 0;
            }
        } else ResetingDarkMonolithLocation = Date.now() + 30 * 1000;
        return;
    }
    let playerPos = getPlayerPos();
    ShowDarkMonolithLocation = ShowDarkMonolithLocation.filter(pos => playerPos.distance(pos) > 10);
    let playerLookingPos = rayTrace((Client.settings.video.getRenderDistance()*16)^2);
    if(playerLookingPos != null) ShowDarkMonolithLocation.filter(pos => playerLookingPos.distance(pos) < 5).forEach(pos => {
        for (let x = -2; x <= 2; x++) {
            for (let z = -2; z <= 2; z++) {
                let block = World.getBlockAt(pos.x+x,pos.y,pos.z+z);
                if(block.getType().getRegistryName() === "minecraft:dragon_egg") {
                    ShowDarkMonolithLocation = [pos];
                    ResetingDarkMonolithLocation = 0;
                    return;
                } else if(World.getBlockAt(pos.x+x,pos.y-1,pos.z+z).getType().getRegistryName() != "minecraft:air") {
                    ShowDarkMonolithLocation = ShowDarkMonolithLocation.filter(p => p != pos);
                }
            }
        }
    })
}).setDelay(1)

register("step", () => {
    if(!location.inSkyblock) return;
    if(settings.DarkMonolithFinder != 2) return;
    if(location.island != "Dwarven Mines") return;
    DarkMonolithLocation.forEach(pos => {
        for (let x = -2; x <= 2; x++) {
            for (let z = -2; z <= 2; z++) {
                let block = World.getBlockAt(pos.x+x,pos.y,pos.z+z);
                if(block.getType().getRegistryName() === "minecraft:dragon_egg") {
                    ShowDarkMonolithLocation = [pos];
                    ResetingDarkMonolithLocation = 0;
                    return;
                } else if(World.getBlockAt(pos.x+x,pos.y-1,pos.z+z).getType().getRegistryName() != "minecraft:air") {
                    ShowDarkMonolithLocation = ShowDarkMonolithLocation.filter(p => p != pos);
                }
            }
        }
    })
}).setDelay(2)

register("worldLoad", () => {
    ShowDarkMonolithLocation = DarkMonolithLocation;
    ResetingDarkMonolithLocation = 0;
})

register("chat", (reward) => {
    if(!location.inSkyblock) return;
    if(settings.DarkMonolithFinder == 0) return;
    if(location.island != "Dwarven Mines") return;
    ShowDarkMonolithLocation = [];
}).setCriteria("MONOLITH! You found a mysterious Dark Monolith and were rewarded ${reward}")

//家中防爆
register("playerInteract", (action,pos,event) => {
    if(!settings.NoPickobulusOnIsland || !location.inSkyblock || location.island != "Private Island") return;
    let item = Player.getHeldItem();
    if(item == null) return;
    let lore = item.getLore();
    if(lore.some(line => line.removeFormatting().includes("Ability: Pickobulus  RIGHT CLICK"))) {
        cancel(event);
        ChatLib.chat("§6§l[BZA] §r§e已阻止你在个人岛屿使用爆炸镐技能");
    }
})

//冰川矿井废料提示
let getSuspiciousScrap = 0;
const suspiciousScrap = new Item(newItemStackFrom("minecraft:skull",3,"{HideFlags:254,SkullOwner:{Id:\"6f70f371-2dcd-323d-9609-40f4935de840\",Properties:{textures:[0:{Value:\"ewogICJ0aW1lc3RhbXAiIDogMTcwOTI3NjQwNjQ2MywKICAicHJvZmlsZUlkIiA6ICI0MmIwOTMyZDUwMWI0MWQ1YTM4YjEwOTcxYTYwYmYxMyIsCiAgInByb2ZpbGVOYW1lIiA6ICJBaXJib2x0MDc4IiwKICAic2lnbmF0dXJlUmVxdWlyZWQiIDogdHJ1ZSwKICAidGV4dHVyZXMiIDogewogICAgIlNLSU4iIDogewogICAgICAidXJsIiA6ICJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzMyNDI3ZDAyNmVlOGU4M2Y3NDQyMjc3MmJhZDBhYWU0NGExNmVlY2U3MDg5MDFmYzIwNmE1MWY0NzIwZjcxZWYiLAogICAgICAibWV0YWRhdGEiIDogewogICAgICAgICJtb2RlbCIgOiAic2xpbSIKICAgICAgfQogICAgfQogIH0KfQ\u003d\u003d\"}]}},display:{Lore:[0:\"§7Found within the deepest depths of\",1:\"§7the §bGlacite Tunnels§7. Place in the\",2:\"§7§6Fossil Excavator §7to begin excavating!\",3:\"\",4:\"§7§8It\u0027s pretty heavy... maybe something\",5:\"§8valuable lies within?\",6:\"\",7:\"§9§lRARE\"],Name:\"§9Suspicious Scrap\"},ExtraAttributes:{id:\"SUSPICIOUS_SCRAP\"}}"));
register("chat", () => {
    if(!location.inSkyblock || location.island != "Mineshaft") return;
    getSuspiciousScrap++;
}).setCriteria("EXCAVATOR! You found a Suspicious Scrap!")

register("renderOverlay", () => {
    if(!settings.GlaciteMineshaftWaypoints) return;
    if(guiMover.gui.isOpen()) {
        suspiciousScrap.draw(guiMover.settings.SuspiciousScrap.x,guiMover.settings.SuspiciousScrap.y,guiMover.settings.SuspiciousScrap.s);
        DrawString("    §e0/1",guiMover.settings.SuspiciousScrap.x,guiMover.settings.SuspiciousScrap.y + 2 * guiMover.settings.SuspiciousScrap.s,guiMover.settings.SuspiciousScrap.s,true);
        return;
    }
    if(!location.inSkyblock || location.island != "Mineshaft") return;
    suspiciousScrap.draw(guiMover.settings.SuspiciousScrap.x,guiMover.settings.SuspiciousScrap.y,guiMover.settings.SuspiciousScrap.s);
    DrawString("    " + (getSuspiciousScrap >= 5 ? "§a" : "§e") + getSuspiciousScrap + "/5",guiMover.settings.SuspiciousScrap.x,guiMover.settings.SuspiciousScrap.y + 2 * guiMover.settings.SuspiciousScrap.s,guiMover.settings.SuspiciousScrap.s,true);
})

//冰川矿井出口
let enterMineshaft = false;
let enterMineshaftTime = 0;
let mineshaftOnwer = false;
let waitingPartyTransfer = false;
register("tick", () => {
    if(!enterMineshaft) return;
    if(!location.island || !location.location || location.location == "None") return;
    if(location.inSkyblock && location.island == "Mineshaft"){
        if(settings.GlaciteMineshaftWaypoints) waypoints.addWaypoint("&6出口",Player.getX(),Player.getY(),Player.getZ(),0);

        if(mineshaftOnwer) {
            enterMineshaftTime = Date.now();
            if(settings.GlaciteMineshaftWarp > 1) {
                partylist.get(party => {
                    if(party[Player.getUUID()] === "LEADER") {
                        if(settings.GlaciteMineshaftWarp == 4) setTimeout(()=>{ ChatLib.command("p warp"); }, 500);
                    } else {
                        ChatLib.command("pc !ptme");
                        if(settings.GlaciteMineshaftWarp == 4) waitingPartyTransfer = true;
                    }
                })
            }
        }
    }
    enterMineshaft = false;
    mineshaftOnwer = false;
})

register("worldLoad", () => {
    waitingPartyTransfer = false;
    enterMineshaft = true;
    enterMineshaftTime = 0;
    getSuspiciousScrap = 0;
    setTimeout(() => { enterMineshaft = false; }, 20000);
})

//看看你是否为矿井的房主
let serverName = "";
register("chat", (player,event) => {
    if(stripRank(player) != Player.getName()) return;
    if(!location.inSkyblock || location.island != "Dwarven Mines") return;
    mineshaftOnwer = true; serverName = location.server;
    setTimeout(() => { if(location.server == serverName) mineshaftOnwer = false; }, 60000);
}).setCriteria(/[-]+->newLine<-(.+) entered Glacite Mineshafts!->newLine<-[-]+/)

//被转让队长后把队伍成员都拉进冰川矿井
register("chat", (player1,message1,player2) => {
    if(!location.inSkyblock || location.island != "Mineshaft") return;
	if(waitingPartyTransfer && Player.getName() == stripRank(player2)) ChatLib.command("p warp");
}).setChatCriteria(/(.+)( has promoted |将组队移交给了|已将)(.+)( to Party Leader||提拔为组队队长，(.+)现在为组队管理员)/)
register("chat", (player2,player1) => {
    if(!location.inSkyblock || location.island != "Mineshaft") return;
	if(waitingPartyTransfer && Player.getName() == stripRank(player2)) ChatLib.command("p warp");
}).setChatCriteria(/The party was transferred to (.+) by (.+)/)

//冰冻尸体
const CorpseID = {"LAPIS_ARMOR_LEGGINGS":"§b§lLapis","ARMOR_OF_YOG_LEGGINGS":"§6§lUmber","MINERAL_LEGGINGS":"§f§lTungsten","VANGUARD_LEGGINGS":(isModLoaded("skyblockaddons") ? "§Z" : "§b") + "§lVanguard"};
let Corpse = [];
register("step", () => {
    if(!settings.GlaciteMineshaftWaypoints || !location.inSkyblock || location.island != "Mineshaft") return;
    Corpse = [];
    World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => !e.isDead() && !e.isInvisible() && e.getEntity().func_71124_b(2)).forEach(e => {
        const ID = getItemSBID(new Item(e.getEntity().func_71124_b(2)));
        if(ID && CorpseID[ID]) {
            Corpse.push({name:CorpseID[ID],x:e.getX(),y:e.getY()+2,z:e.getZ()});
        }
    })
}).setDelay(1)
register("renderWorld", () => {
    if(!settings.GlaciteMineshaftWaypoints || !location.inSkyblock || location.island != "Mineshaft") return;
    Corpse.forEach(e => {
        Tessellator.drawString(e.name,e.x,e.y,e.z,0,true,0.8,true);
        if(enterMineshaftTime + 60000 > Date.now() && e.name.removeFormatting() == "Vanguard")
            Tessellator.drawString(`§b矿井入口将在 §e${Math.floor((60000 + enterMineshaftTime - Date.now()) / 1000)} §b秒后关闭`,e.x,e.y+1,e.z,0,true,0.05,false);
    })
})
register("worldLoad", () => { Corpse = []; })

//冰川矿井传送门提示
let portalTimer = 0;
register("chat", () => {
    if(!settings.GlaciteMineshaftWarp || !location.inSkyblock || location.island != "Dwarven Mines") return;
    Client.showTitle(settings.GlaciteMineshaftWarp == 4 ? "§bMineshaft PORTAL" : "§a§lPORTAL",settings.GlaciteMineshaftWarp == 4 ? "§3在进洞后将会尝试/p warp" : "§bGlacite Mineshaft",0,50,10);
    World.playSound("mob.enderdragon.growl",1,1);
    portalTimer = Date.now() + 30000;
}).setCriteria("WOW! You found a Glacite Mineshaft portal!")

register("renderWorld", () => {
    if(settings.GlaciteMineshaftWarp == 0 || !location.inSkyblock || location.island != "Dwarven Mines") return;
    if(portalTimer < Date.now()) return;
    World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName().includes(Player.getName()) && e.getName().removeFormatting().endsWith("'s Mineshaft Portal")).forEach(e => {
        BeaconBeam(e.getX()-0.5,e.getY(),e.getZ()-0.5,0,1,1,1,true);
        Tessellator.drawString("§a" + timedisplay(portalTimer - Date.now()),e.getX(),e.getY()+1,e.getZ(),0,false,0.05,false);
    })
})

register("worldLoad", () => { portalTimer = 0; })

//冰川洞坐标点
const GemstoneColor = {Onyx:"§0",Aquamarine:"§9",Citrine:"§6",Peridot:"§2"}
const GemstonePos = {
    Onyx : [new Vec3i(-69,131,407),new Vec3i(3,136,390),new Vec3i(77,120,409)],
    Aquamarine:[new Vec3i(51,118,302),new Vec3i(-2,140,436),new Vec3i(59,152,399),new Vec3i(87,152,325)],
    Citrine:[new Vec3i(37,120,386),new Vec3i(-92,144,265),new Vec3i(-52,128,410)],
    Peridot:[new Vec3i(-74,124,458),new Vec3i(-77,121,281),new Vec3i(-62,148,301),new Vec3i(91,123,397)]
};
register("renderWorld", () => {
    if(!settings.GlaciteTunnelsWaypoints || !location.inSkyblock || location.island != "Dwarven Mines" || 
     (location.location != "Dwarven Base Camp" && location.location != "Glacite Tunnels" && location.location != "Great Glacite Lake")) return;
    TabList.getNames().filter(e => e.removeFormatting().includes(" Gemstone Collector: ")).forEach(e => {
        const gemstoneName = e.removeFormatting().trim().replace(/ Gemstone Collector: .+/,"");
        GemstonePos[gemstoneName].forEach(pos => {
            Tessellator.drawString(GemstoneColor[gemstoneName] + gemstoneName,pos.x,pos.y,pos.z,0,true,0.8,true);
        })
    })
})

//大块冰川位置
const GreatGlaciteWaypoints = [
    [new Vec3i(52,154,274), new Vec3(57.25,154.8,274.25)],
    [new Vec3i(18,164,303), new Vec3(22.5,164.6,302.5)],
    [new Vec3i(99,135,318), new Vec3(103.25,135.6,318.25)],
    [new Vec3i(110,139,337), new Vec3(110.25,140.25,332.6)],
    [new Vec3i(-32,130,332), new Vec3(-31.75,128.6,332.25)],
]
register("renderWorld",() => {
    if(!settings.GreatGlaciteWaypoints || !location.inSkyblock || location.island != "Dwarven Mines" || 
     (location.location != "Dwarven Base Camp" && location.location != "Glacite Tunnels" && location.location != "Great Glacite Lake")) return;
    GreatGlaciteWaypoints.forEach(e => {
        drawQuadsAtPos(e[0].x,e[0].y,e[0].z,0,1,1,0.3,1,1,0.02);
        Tessellator.drawString("§bGreat Glacite",e[0].x+0.5,e[0].y,e[0].z+0.5,0,true,0.6,true);
        if(getPlayerPos().distance(e[0]) < 5) {
            drawQuadsAtPos(e[1].x,e[1].y,e[1].z,0,1,1,0.3,0.5,0.5,0.5,true);
            drawQuadsAtPos(e[1].x,e[1].y,e[1].z,0.2,0.2,1,1,0.5,0.5,0.5);
        }
    })
})

//手持钻机或拳套时阻止手臂晃动
register("renderHand", (event) => {
    if(!settings.DrillSwing || !location.inSkyblock) return;
    const heldItem = Player.getHeldItem();
    if(!heldItem) return;
    const itemID = getItemSBID(heldItem);
    if(itemID && (itemID.includes("DRILL") || itemID.includes("GAUNTLET")))
        Player.getPlayer().field_70733_aJ = 0;
})


}